package org.lan.jdbc.utils;

import org.lan.jdbc.configuration.ConfigurationHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 改类封装了JDBC读取配置，以及获取连接和關閉的操作
 * <p>
 * 2016/8/5.
 *
 * @author jiahua-lan
 */
public final class JDBCUtils {

    private final static Logger LOGGER = LoggerFactory.getLogger(JDBCUtils.class);

    private static ThreadLocal<Connection> threadLocalConnection = new ThreadLocal<Connection>();

    static {
        try {
            Class.forName(ConfigurationHelper.getDRIVER());
        } catch (ClassNotFoundException e) {
            LOGGER.error("Can't find the JDBC_DRIVER", e);
        }
    }

    public static Connection getConnection() {
        Connection connection = threadLocalConnection.get();
        if (connection == null) {
            try {
                connection = DriverManager.getConnection(ConfigurationHelper.getURL(), ConfigurationHelper.getUSERNAME(), ConfigurationHelper.getPASSWORD());
            } catch (SQLException e) {
                LOGGER.error("Open connection failed", e);
            } finally {
                threadLocalConnection.set(connection);
            }
        }
        return connection;
    }

    public static void closeConnection() {
        Connection connection = threadLocalConnection.get();
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                LOGGER.error("Close connection failed", e);
            } finally {
                threadLocalConnection.remove();
            }
        }
    }
}
